package ru.averta.notes.service.security;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import ru.averta.notes.domain.User;
import ru.averta.notes.service.security.login.SecurityUser;

@Service
public class SecurityServiceImpl implements SecurityService {

    @Autowired
    @Qualifier("org.springframework.security.authenticationManager")
    AuthenticationManager authManager;

    public SecurityContext getSecurityContext() {
        return SecurityContextHolder.getContext();
    }

    public void setSecurityContext(SecurityContext securityContext) {
        SecurityContextHolder.setContext(securityContext);
    }

    public String getCurrentUserName() {
        Authentication auth = getAuthentication();
        if (auth == null || auth.getPrincipal() == null) {
            return null;
        }
        if (auth.getPrincipal() instanceof UserDetails) {
            return ((UserDetails) auth.getPrincipal()).getUsername();
        } else {
            return auth.getPrincipal().toString();
        }
    }

    public boolean isLoggedIn() {
        //return (!getCurrentUserName().equals(""));

        if (getSecurityContext() == null) {
            return false;
        } else if (getSecurityContext().getAuthentication() == null) {
            return false;
        } else if (!getSecurityContext().getAuthentication().isAuthenticated()) {
            return false;
        } else {
            return true;
        }
    }

    private Authentication getAuthentication() {
        return getSecurityContext().getAuthentication();
    }

    public User getCurrentUser() {
        if (isLoggedIn()) {
            SecurityUser securityUser = (SecurityUser) getSecurityContext().getAuthentication().getPrincipal();
            return securityUser.getUser();
        } else {
            return null;
        }
    }

    @Override
    public void loginAs(String login, String password) {
        Authentication request = new UsernamePasswordAuthenticationToken(login, password);
        Authentication result = authManager.authenticate(request); //Получаем данные, роли и т.д.
        SecurityContextHolder.getContext().setAuthentication(result); //Логинимся под пользователем

    }
}
